package com.codeest.geeknews.ui.main.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;

import com.codeest.geeknews.R;
import com.codeest.geeknews.app.App;
import com.codeest.geeknews.app.Constants;
import com.codeest.geeknews.base.GestureImageViewSetting;
import com.codeest.geeknews.base.SimpleActivity;
import com.codeest.geeknews.model.bean.PhotoBean;
import com.codeest.geeknews.model.bean.RealmLikeBean;
import com.codeest.geeknews.model.db.RealmHelper;
import com.codeest.geeknews.ui.main.adapter.PaintingsPagerAdapter;
import com.codeest.geeknews.util.ShareUtil;
import com.codeest.geeknews.util.SystemUtil;
import com.codeest.geeknews.util.ToastUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.List;

import butterknife.BindView;
import io.reactivex.functions.Consumer;

/**
 * Created by admin on 2017/8/3.
 */

public class PhotoDetailActivity extends SimpleActivity implements ViewPager.OnPageChangeListener {
    public static Bitmap bitmap;

    public interface ImageLoadCallback {
        void onLoaded(int position, Bitmap resource);
    }
    //---------------------------------

    @BindView(R.id.toolbar)
    Toolbar toolBar;
    @BindView(R.id.paintings_view_pager)
    ViewPager viewPager;
    @BindView(R.id.image)
    ImageView image;


    private static int ACTION_SAVE = 0x00;
    private static int ACTION_SHARE = 0x01;

    RxPermissions rxPermissions;
    RealmHelper mRealmHelper;
    MenuItem menuItem;

    boolean isLiked;
    String url;
    String id;
    private List<PhotoBean> mImageInfos;
    int singleTapCount = 0;
    private int mClickPosition;
    private int currentPosition;
    private PaintingsPagerAdapter mAdapter;
    GestureImageViewSetting setting;

    @Override
    protected int getLayout() {
        return R.layout.activity_photo_detail;
    }


    @Override
    protected void initEventAndData() {
        findViewById(android.R.id.content).setBackgroundResource(android.R.color.black);
        //viewPager.setVisibility(View.INVISIBLE);
        setToolBar(toolBar, "");
        mRealmHelper = App.getAppComponent().realmHelper();
        Intent intent = getIntent();
        mClickPosition = intent.getExtras().getInt(Constants.IT_PHOTO_CLICK_POSITION);
        mImageInfos = intent.getExtras().getParcelableArrayList(Constants.IT_PHOTO_INFOS);
        url = mImageInfos.get(mClickPosition).getUrl();
        id = mImageInfos.get(mClickPosition).getId();

        image.setImageBitmap(bitmap);

        final ImageLoadCallback imageLoadCallback = new ImageLoadCallback() {
            @Override
            public void onLoaded(int position, Bitmap resource) {
                Log.i("resource ", resource.getByteCount() + "");
                //BitmapCacheUtil.getInstance().addBitmapToMemoryCache(String.valueOf(position), resource);
            }
        };

        final PaintingsPagerAdapter.OnSingleTapUpListener imageClickListener = new PaintingsPagerAdapter.OnSingleTapUpListener() {
            @Override
            public void onSingleTapConfirmed(View view) {
                if (singleTapCount == 0) {
                    hideSystemUI();
                    toolBar.animate().setDuration(getResources().getInteger(android.R.integer.config_mediumAnimTime)).translationY(-(toolBar.getHeight() /*+ StatusBarUtil.getStatusBarHeight(PhotoDetailActivity.this)*/));
                    singleTapCount = 1;
                } else {
                    toolBar.animate().setDuration(getResources().getInteger(android.R.integer.config_mediumAnimTime)).translationY(0);
                    showSystemUI();
                    singleTapCount = 0;
                }
            }
        };
        setting = new GestureImageViewSetting.Builder(this)
                .setExitEnabled(true)
                .setFillViewport(true)
                .setOverscrollXEnabled(true)
                .setOverscrollYEnabled(true)
                .setPanEnabled(true)
                .setRotationEnabled(true)
                .creat();
        mAdapter = new PaintingsPagerAdapter(viewPager, mImageInfos, /*bitmap,*/ mClickPosition, setting, imageLoadCallback, imageClickListener);
        viewPager.setAdapter(mAdapter);
        viewPager.addOnPageChangeListener(this);
        viewPager.setCurrentItem(mClickPosition);
        //viewPager.setPageTransformer(true, new ParallaxPageTransformer(R.id.gestureImageView));
        //onPageSelected(mClickPosition); // Manually calling for first item
        image.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (image != null) {
                    image.setVisibility(View.GONE);
                }
            }
        }, 1000);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        bitmap = null;
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.girl_menu, menu);
        menuItem = menu.findItem(R.id.action_like);
        setLikeState(mRealmHelper.queryLikeId(id));
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.action_like:
                if (isLiked) {
                    item.setIcon(R.mipmap.ic_toolbar_like_n);
                    mRealmHelper.deleteLikeBean(this.id);
                } else {
                    item.setIcon(R.mipmap.ic_toolbar_like_p);
                    RealmLikeBean bean = new RealmLikeBean();
                    bean.setId(this.id);
                    bean.setImage(url);
                    bean.setType(Constants.TYPE_GIRL);
                    bean.setTime(System.currentTimeMillis());
                    mRealmHelper.insertLikeBean(bean);
                }
                break;
            case R.id.action_save:
                checkPermissionAndAction(ACTION_SAVE);
                break;
            case R.id.action_share:
                checkPermissionAndAction(ACTION_SHARE);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void setLikeState(boolean state) {
        if (state) {
            menuItem.setIcon(R.mipmap.ic_toolbar_like_p);
            isLiked = true;
        } else {
            menuItem.setIcon(R.mipmap.ic_toolbar_like_n);
            isLiked = false;
        }
    }

    @Override
    public void onBackPressedSupport() {
        if (currentPosition == mClickPosition) {
            viewPager.setVisibility(View.GONE);
            image.setVisibility(View.VISIBLE);
        }
        if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
            pop();
        } else {
            if (viewPager.getCurrentItem() == mClickPosition && Build.VERSION.SDK_INT > 21) {
                finishAfterTransition();
            } else {
                finish();
                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
            }
        }
    }

    private void checkPermissionAndAction(final int action) {
        if (rxPermissions == null) {
            rxPermissions = new RxPermissions(this);
        }

        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean granted) {
                        if (granted) {
                            ImageView imageView = (ImageView) mAdapter.getPrimaryItem();
                            if (action == ACTION_SAVE) {
                                bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
                                SystemUtil.saveBitmapToFile(mContext, url, bitmap, imageView, false);
                            } else if (action == ACTION_SHARE) {
                                ShareUtil.shareImage(mContext, SystemUtil.saveBitmapToFile(mContext, url, bitmap, imageView, true), "分享一只妹纸");
                            }
                        } else {
                            ToastUtil.shortShow("获取写入权限失败");
                        }
                    }
                });
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        // no-op
    }

    @Override
    public void onPageSelected(int position) {
        //setToolBar();
        url = mImageInfos.get(position).getUrl();
        id = mImageInfos.get(position).getId();
        currentPosition = position;
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        // no-op
    }
}

